/*
 * @author: huangww
 * @Date: 2021-02-26 14:40:01
 * @LastEditTime: 2021-02-26 14:44:22
 * @FilePath: \fmgr\src\core\util\Utils.ts
 */
class Utils {
  // 获取参数
  public static getParam(key: string, url: string) {
    let str = url.substr(url.indexOf("?") + 1);
    let arr = str.split("&");
    let params = [];
    for (let i in arr) {
      params = arr[i].split("=");
      if (key == params[0]) {
        return params[1];
      }
    }
    return false;
  }

  //求两点距离
  public static getDistance(x1: number, y1: number, x2: number, y2: number) {
    var _x: number = Math.abs(x1 - x2);
    var _y: number = Math.abs(y1 - y2);
    return Math.sqrt(_x * _x + _y * _y);
  }

  public static copyMsg(msg: string) {
    let message = msg;
    let input = document.createElement("input");
    input.value = message;
    document.body.appendChild(input);
    input.select();
    input.setSelectionRange(0, input.value.length),
      document.execCommand('Copy');
    document.body.removeChild(input);
    // egret.log("复制成功");
  }

  // 加载远程图片
  public static loadImg(image: eui.Image, imgUrl: string) {
    let imageLoader = new egret.ImageLoader();
    imageLoader.crossOrigin = "anonymous";
    imageLoader.load(imgUrl);
    imageLoader.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
      let imageLoader = <egret.ImageLoader>event.currentTarget;
      let texture = new egret.Texture();
      texture.bitmapData = imageLoader.data;
      image.source = texture;
      image.anchorOffsetX = image.width / 2;
      image.anchorOffsetY = image.height / 2;
    }, this);
  }

  /**
   * 获取字符串指定长度的部分，超出用“...”替代，中文、特殊符号算两个字符
   * @param str 字符串
   * @param len 截取的长度，中文、特殊符号算两个字符
   * @param ext 超出部分替换字符
   */
  public static getStringByLength(str: string, len = 12, ext = "..."): string {
    // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxx",str); 
    if (str == null || str == undefined) {
      str = "";
      return;
    }

    // 去掉转义字符
    str = str.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');
    // 去掉特殊字符
    str = str.replace(/[\-\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\<\>\?]/g, '');

    let realLength = str.length;
    let charCode = -1;
    let Zcharlength = 0; //中文长度

    let afterlength = 0; //中文转后长度，实际应用长度
    for (let i = 0; i < realLength; i++) {
      charCode = str.charCodeAt(i);
      if (charCode >= 0 && charCode <= 128) {
        afterlength += 1
      } else {
        afterlength += 2;
        if (afterlength <= len) {
          Zcharlength++;
        }
      }
    }
    if (afterlength > len) {
      str = str.substr(0, len - Zcharlength);
      str += ext;
    }
    return str;
  }
}